<?php
/**
 * Template Name: Registration Url Page
 *
 */

get_header(); ?>
    <div class="left-main large-8 medium-8 columns no-padding">
        <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
        <div class="row">
            <h3><?php the_title(); ?></h3>
        </div>
		<div class="contact row">
            <div class="main-contact">
                <?php the_content(); ?>
                <!-- Register form -->
                <form id="register-form" method="post" action="<?php echo $current_page->guid; ?>">
                    <div class="row">
                        <div class="small-8">
                            <div class="row">
                                <div class="small-3 columns">
                                    <label for="right-label" class="right inline">Name</label>
                                </div>
                                <div class="small-9 columns">
                                    <input type="text" name="txtname" id="right-label" placeholder="Your name...">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="small-8">
                            <div class="row">
                                <div class="small-3 columns">
                                    <label for="right-label" class="right inline">Email</label>
                                </div>
                                <div class="small-9 columns">
                                    <input type="text" name="txtemail" id="right-label" placeholder="Your email...">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="small-8">
                            <div class="row">
                                <div class="small-3 columns">
                                    <label for="right-label" class="right inline">URL</label>
                                </div>
                                <div class="small-9 columns">
                                    <input type="text" name="txturl" placeholder="Enter your URL...">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="small-8">
                            <div class="row">
                                <div class="small-3 columns">
                                    
                                </div>
                                <div class="small-9 columns">
                                    <input type="submit" name="submit" size="20" value="submit" />
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
                <!-- /Register form -->

                <?php 

                    /**
                    
                        TODO:
                        - Insert post with drap status: get title, description, thumbnail images
                        - Insert custom meta post: name - email - url
                    
                    **/
                    
                    if (isset($_POST['submit']) && $_POST['submit'] == 'submit') {

                        //Get data
                        require_once ('libs/simple_html_dom.php');

                        $url = $_POST['txturl'];

                        $file_headers = @get_headers($url);
                        if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
                            exit('URL Die!');
                        }

                        // get DOM from URL or file
                        $html = file_get_html($url);
                        //parsing begins here:
                        $doc = new DOMDocument();
                        @$doc->loadHTML($html);
                        $nodes = $doc->getElementsByTagName('title');

                        //get and display what you need:
                        $title = $nodes->item(0)->nodeValue;

                        $metas = $doc->getElementsByTagName('meta');

                        for ($i = 0; $i < $metas->length; $i++)
                        {
                            $meta = $metas->item($i);
                            if($meta->getAttribute('name') == 'description'){
                                $description = $meta->getAttribute('content');
                            }
                            if($meta->getAttribute('name') == 'keywords'){
                                $keywords = $meta->getAttribute('content');
                            }
                        }

                        //Get & Filter images by width & height
                        $minWidth = 200;
                        $minHeight = 200;
                        foreach ($html->find('img') as $image) {
                            $image_url = $image->src;
                            if ( $img = @GETIMAGESIZE($image_url) )
                            {
                                $size = getimagesize($image_url);
                                if ( $size[0] > $minWidth && $size[1] > $minHeight ) {
                                    break;
                                }
                            } 
                            else
                            {
                                $image_url = "";
                            }
                        }

                        // Insert post to worpress Cat
                        $Cats = 1;
                        $my_post = array(
                          'post_title'    => $title,
                          'post_excerpt'  => $description,
                          'post_content'  => $description,
                          'post_status'   => 'Pending',
                          'post_author'   => 1,
                          'post_category' => array($Cats)
                        );

                       $post_id = wp_insert_post($my_post, $wp_error);

                       // echo 'Error: '. $wp_error .'<br/>';
                       // echo "Inserted Post ID: $post_id";

                       if (!$wp_error && $post_id) {

                           // Add post meta
                            add_post_meta( $post_id, 'author_email', $_POST['txtemail'] );
                            add_post_meta( $post_id, 'author_name', $_POST['txtname'] );
                           

                            //Set post-tags
                            wp_set_post_tags( $post_id, $keywords, true );
                       
                            // Add Featured Image to Post
                            if (isset($image_url) && $image_url != ""){

                                $upload_dir = wp_upload_dir(); // Set upload folder
                                $image_data = file_get_contents($image_url); // Get image data
                                $filename   = basename($image_url); // Create image file name

                                // Check folder permission and define file location
                                if( wp_mkdir_p( $upload_dir['path'] ) ) {
                                    $file = $upload_dir['path'] . '/' . $filename;
                                } else {
                                    $file = $upload_dir['basedir'] . '/' . $filename;
                                }

                                // Create the image  file on the server
                                file_put_contents( $file, $image_data );

                                // Check image file type
                                $wp_filetype = wp_check_filetype( $filename, null );

                                // Set attachment data
                                $attachment = array(
                                    'post_mime_type' => $wp_filetype['type'],
                                    'post_title'     => sanitize_file_name( $filename ),
                                    'post_content'   => '',
                                    'post_status'    => 'inherit'
                                );

                                // Create the attachment
                                $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

                                // Include image.php
                                require_once(ABSPATH . 'wp-admin/includes/image.php');

                                // Define attachment metadata
                                $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

                                // Assign metadata to attachment
                                wp_update_attachment_metadata( $attach_id, $attach_data );

                                // And finally assign featured image to post
                                set_post_thumbnail( $post_id, $attach_id );
                            }//End if image exist
                        }
                        echo '<br/>Insert success...!';
                    }
                 ?>    

            </div><!---end main contact-->
        </div><!-- end contact-->
        <?php endwhile; // end of the loop. ?>
    </div><!---end left-main-->

<?php get_sidebar('page'); ?>
<?php get_footer(); ?> 

<script type="text/javascript">

(function($,W,D)
{
    var JQUERY4U = {};

    JQUERY4U.UTIL =
    {
        setupFormValidation: function()
        {
            //form validation rules
            $('#register-form').validate({
                rules: {
                    txtname: "required",
                    txtemail: {
                        required: true,
                        email: true
                    },
                    txturl: {
                        required: true,
                        url: true
                    }
                },
                messages: {
                    txtname: "<?php echo _e( '* Please enter your name'); ?>",
                    txtemail: "<?php echo _e( '* Please enter a valid email address'); ?>",
                    txturl: "<?php echo _e( '* Please enter correct url start with http://'); ?>"
                },
                submitHandler: function(form) {
                    form.submit();
                }
            });
        }
    }

    //when the dom has loaded setup form validation rules
    $(D).ready(function($) {
        JQUERY4U.UTIL.setupFormValidation();
    });

})(jQuery, window, document);

</script>